package com.whut.controller;

import com.whut.util.SendMessageUtil;
import com.whut.util.SystemUtil;
import com.whut.util.ThreadUtil;
import com.whut.util.ZipUtil;
import com.whut.vo.ResponseMsg;
import com.whut.wesocket.PollWebSocketServlet;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.security.NoSuchAlgorithmException;

import static com.whut.util.DateUtil.getNowTimeMS;
import static com.whut.util.SystemUtil.*;


/**
 * 数据分析接口，云计算、传感器诊断等
 *
 * @author Sandeepin
 */
@Controller
@RequestMapping("/analysis")
public class AnalysisController {
    private static final Logger logger = Logger.getLogger(AnalysisController.class);
    private static final String fileSavePath="/usr/local/tomcat/webapps/ROOT/file/compute/";
    @Autowired
    private PollWebSocketServlet webSocketServlet;

    /**
     * 获取MD5的前8位
     *
     * @param request HttpServletRequest
     * @return md5
     * @throws NoSuchAlgorithmException 异常
     */
    @RequestMapping("/md5")
    @ResponseBody
    public String statidata(HttpServletRequest request) throws NoSuchAlgorithmException {
        String md5str = getMd5(getNowTimeMS() + request.getSession().toString());
        return md5str.substring(0, 8);
    }

    /**
     * Spark分布式计算任务上传py文件和数据
     *
     * @param file    文件
     * @param request http
     * @return 信息
     */
    @RequestMapping("/sparkupload")
    @ResponseBody
    public ResponseMsg uploadbin(@RequestParam MultipartFile file, HttpServletRequest request) {
        ResponseMsg j = new ResponseMsg();
        if (file.isEmpty()) {
            j.setMsg("请选择要上传的spark文件！");
            return j;
        }
        // 服务器上传的spark文件所在路径
        String webSaveSparkFilePath = "/usr/local/tomcat/webapps/ROOT/file/compute/";
        if (isWindows()) {
            webSaveSparkFilePath = fileSavePath;
        }
        // 获取上传文件的原名 例464e7a80_710229096@qq.com.zip
        String saveFileName = file.getOriginalFilename();
        // 去掉后缀.zip 例464e7a80_710229096@qq.com
        String fileBaseName = FilenameUtils.getBaseName(saveFileName);
        // 获取 md5value email
        String[] tmp = fileBaseName.split("_");
        String md5value = "00000000";
        String email = "sandeepin@qq.com";
        if (tmp.length == 2) {
            md5value = tmp[0];
            email = tmp[1];
        }try {
            // 检测md5是否冲突
            File files = new File(webSaveSparkFilePath);
            File[] tempList = files.listFiles();
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isDirectory()) {
                    System.out.println("文件夹：" + tempList[i]);
                    String md5files = tempList[i].toString();
                    if (md5files.contains(md5value)) {
                        SendMessageUtil.sendMessage(md5value, "【警告】md5冲突，请刷新页面重试！", webSocketServlet);
                        j.setMsg("md5冲突！");
                        return j;
                    }
                }
            }
            // 把上传的文件放到服务器的文件夹下
            String saveFilePath = webSaveSparkFilePath + md5value + "\\";
            if (!isWindows()) {
                saveFilePath = webSaveSparkFilePath + md5value + "/";
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(saveFilePath, saveFileName));

            // 检测用户的文件是否套了一层文件夹
            String firstDir = isDirZipFile(saveFilePath + saveFileName);
            if (!"run.py".equals(firstDir)) {
                // 解压文件
                ZipUtil.decompress(saveFilePath + saveFileName);
                // 强制删除zip文件
                boolean deleteZipSuccess = SystemUtil.forceDelete(new File(saveFilePath, saveFileName));
                // 创建无外层文件夹的zip文件
                System.out.println(saveFilePath + firstDir + "   del:"+deleteZipSuccess);
                if (deleteZipSuccess) {
                    ZipUtil.compress(saveFilePath + firstDir, saveFilePath + saveFileName, false);
                }
                // 删除文件夹
                File firstDirAllPath = new File(saveFilePath + firstDir);
                deleteAllFilesOfDir(firstDirAllPath);
            }
            // [异步]开始远程传输文件到spark服务器
            SendMessageUtil.sendMessage(md5value, "上传成功...", webSocketServlet);
            ThreadUtil t1 = new ThreadUtil("sparkCompute-" + md5value, saveFilePath, saveFileName,
                    md5value, email, webSocketServlet);
            t1.start();

            // 反馈用户信息
            j.setSuccess(true);
            j.setMsg("上传成功！");
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return j;
    }
}
